package com.android.manghe.mine.fragment

import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.base.frame.extend.IRefresh
import com.android.base.frame.extend.IStateController
import com.android.base.frame.title.ETitleType
import com.android.base.frame.view.MVPFragment
import com.android.base.frame.view.XStateController
import com.android.base.tools.Glide.GlideHelper
import com.android.manghe.R
import com.android.manghe.config.events.RefreshOrdersEvent
import com.android.manghe.mine.activity.CheckFreightActivity
import com.android.manghe.mine.activity.MarketOrderDetailActivity
import com.android.manghe.mine.model.DirectBuyOrderList
import com.android.manghe.mine.presenter.PAllOrder
import com.android.manghe.view.AutoHeightLayoutManager
import com.android.manghe.zhuli.activity.ZhuLiProgressActivity
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.chad.library.adapter.base.util.MultiTypeDelegate
import com.eightbitlab.rxbus.Bus
import com.eightbitlab.rxbus.registerInBus
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import kotlinx.android.synthetic.main.fragment_my_kan.recyclerView
import kotlinx.android.synthetic.main.fragment_my_kan.refreshLayout
import kotlinx.android.synthetic.main.fragment_my_order.*


class AllOrderFragment : MVPFragment<PAllOrder>(), IRefresh, IStateController<XStateController> {
    override fun getStateView(): XStateController {
        return mView.findViewById(R.id.xStateController)
    }

    private var mAdapter: AllOrderAdapter? = null

    override fun showToolBarType(): ETitleType {
        return ETitleType.NO_TITLE
    }

    override fun getRefreshView(): SmartRefreshLayout {
        return mView!!.findViewById(R.id.refreshLayout)
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_my_order
    }

    override fun initData(savedInstanceState: Bundle?, parent: View?) {

    }

    override fun onDestroy() {
        super.onDestroy()
        Bus.unregister(this)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mAdapter = AllOrderAdapter(this, mContext, arrayListOf())
        recyclerView.layoutManager =
            LinearLayoutManager(mContext)
        recyclerView.adapter = mAdapter
        p.setType(0)
        p.loadData(true)

        Bus.observe<RefreshOrdersEvent>().subscribe {
            p.loadData(true)
        }.registerInBus(this)

        mAdapter!!.setOnItemClickListener { adapter, _, position ->
            val orderInfo = adapter.data[position] as DirectBuyOrderList.DataBean.ListBean
//            ZhuLiProgressActivity.showActivity(activity!!, orderInfo.order_sn, 20f,
//                orderInfo.goods_item[0].thumb, orderInfo.goods_item[0].name)

            if (TextUtils.equals("0", orderInfo.is_exempt)) {
                //原价购买，进入订单详情界面
                MarketOrderDetailActivity.showActivity(mContext, orderInfo.order_sn)
            } else if (TextUtils.equals("1", orderInfo.is_exempt)) {
                if (orderInfo.distance_amount < 100) {
                    //助力未完成，进入助力进度界面
                    if (orderInfo.goods_item[0] != null) {
                        ZhuLiProgressActivity.showActivity(
                            activity!!, orderInfo.order_sn, orderInfo.distance_amount,
                            orderInfo.goods_item[0].thumb, orderInfo.goods_item[0].name
                        )
                    }
                } else {
                    //助力完成，进入订单详情界面
                    MarketOrderDetailActivity.showActivity(mContext, orderInfo.order_sn)
                }
            }
        }
    }

    override fun onRefresh() {
        p.loadData(true)
    }

    override fun onLoad() {
        p.loadData(false)
    }

    fun update(dataList: List<DirectBuyOrderList.DataBean.ListBean>) {
        mAdapter?.let {
            it.replaceData(dataList)
            if (dataList.isEmpty()) {
                xStateController.showEmpty()
            } else {
                xStateController.showContent()
            }
        }
    }

    fun setCanLoadMore(canLoadMore: Boolean) {
        refreshLayout.isEnableLoadMore = canLoadMore
    }

    fun confirmOrderOk() {
        Bus.send(RefreshOrdersEvent())
    }

    class AllOrderAdapter(
        fragment: AllOrderFragment,
        context: Context,
        data: List<DirectBuyOrderList.DataBean.ListBean>
    ) :
        BaseQuickAdapter<DirectBuyOrderList.DataBean.ListBean, BaseViewHolder>(data) {
        var context: Context? = null
        var fragment: AllOrderFragment? = null

        init {
            this.context = context
            this.fragment = fragment

            multiTypeDelegate = object : MultiTypeDelegate<DirectBuyOrderList.DataBean.ListBean>() {
                override fun getItemType(bean: DirectBuyOrderList.DataBean.ListBean): Int {
                    return if (bean.goods_item.size == 1) 0 else 1
                }
            }
            //添加布局
            multiTypeDelegate
                .registerItemType(0, R.layout.item_all_order_single)//单个商品
                .registerItemType(1, R.layout.item_all_order_multi)//多个商品

        }

        override fun convert(helper: BaseViewHolder, item: DirectBuyOrderList.DataBean.ListBean) {
            helper.setText(R.id.tvOrderNo, "订单号：" + item.order_sn)
            val tvStatus = helper.getView<TextView>(R.id.tvStatus)
            if (TextUtils.equals("0", item.is_exempt)) {
                when (item.status_id) {
                    100 -> {
                        tvStatus.text = "去付款"
                        helper.setText(R.id.tvToPay, "去付款")
                    }
                    101 -> {
                        tvStatus.text = "待发货"
                    }
                    102 -> {
                        tvStatus.text = "已发货"
                    }
                    110 -> {
                        tvStatus.text = if ("1" == item.is_rate) "已晒单" else "已完成"
                    }
                    111 -> {
                        tvStatus.text = "已取消"
                    }
                }
            } else if (TextUtils.equals("1", item.is_exempt)) {
                tvStatus.text = if (item.distance_amount < 100) "助力中" else "助力完成"
                helper.setText(R.id.tvToPay, if (item.distance_amount == 100f) "去付款" else "去助力")
            }
            helper.setVisible(
                R.id.tvToPay,
                (TextUtils.equals(
                    "0",
                    item.is_exempt
                ) && item.status_id == 100) || (TextUtils.equals(
                    "1",
                    item.is_exempt
                ) && item.distance_amount < 100f)
            )
            helper.setGone(R.id.layoutRemindOrder, item.status_id == 102)
            helper.setGone(R.id.tvShowOrder, 110 == item.status_id && "0" == item.is_rate)
            helper.setGone(R.id.layoutAlreadyShai, 110 != item.status_id && "1" == item.is_rate)
            helper.setText(R.id.tvOrderNo, "订单号：${item.order_sn}")
            helper.setText(R.id.tvFreight, "(含运费￥${item.shipping_fee})")
            helper.getView<TextView>(R.id.checkFreight).setOnClickListener {
                //查看物流
                CheckFreightActivity.showActivity(context!!, item.order_sn, false)
            }
            helper.getView<TextView>(R.id.tvRefund).setOnClickListener {
                //退货售后

            }

            when (helper.itemViewType) {
                0 -> {
                    GlideHelper.loadRoundTrans(
                        context,
                        item.goods_item[0].thumb,
                        helper.getView(R.id.ivPic),
                        6
                    )
                    helper.setText(R.id.tvTitle, item.goods_item[0].name)
                    helper.setText(R.id.tvSecondTitle, item.goods_item[0].goods_spec)
                    helper.setText(R.id.tvAmount, "共${item.goods_item[0].buy_num}件")
                    helper.setText(R.id.tvTotalMoney, "合计:￥${item.order_amount}")

                }
                1 -> {
                    val recyclerView = helper.getView<RecyclerView>(R.id.itemRv)
                    recyclerView.layoutManager = AutoHeightLayoutManager(context)
                    val adapter = GoodListAdapter(context!!, item.goods_item)
                    recyclerView.adapter = adapter

                    adapter!!.setOnItemClickListener { _, _, _ ->
                        if (TextUtils.equals("0", item.is_exempt)) {
                            //原价购买，进入订单详情界面
                            MarketOrderDetailActivity.showActivity(mContext, item.order_sn)
                        } else if (TextUtils.equals("1", item.is_exempt)) {
                            if (item.distance_amount < 100) {
                                //助力未完成，进入助力进度界面
                                ZhuLiProgressActivity.showActivity(
                                    context!!, item.order_sn, item.distance_amount,
                                    item.goods_item[0].thumb, item.goods_item[0].name
                                )
                            } else {
                                //助力完成，进入订单详情界面
                                MarketOrderDetailActivity.showActivity(mContext, item.order_sn)
                            }
                        }
                    }

                    var num = 0
                    item.goods_item.forEach {
                        num += it.buy_num.toInt()
                    }
                    helper.setText(R.id.tvAmount, "共${num}件")
                    helper.setText(R.id.tvTotalMoney, "合计:￥${item.order_amount}")
                }
            }
        }
    }

    class GoodListAdapter(
        context: Context,
        data: List<DirectBuyOrderList.DataBean.ListBean.GoodsItemBean>
    ) :
        BaseQuickAdapter<DirectBuyOrderList.DataBean.ListBean.GoodsItemBean, BaseViewHolder>(
            R.layout.item_all_order_good,
            data
        ) {
        var context: Context? = null

        init {
            this.context = context
        }

        override fun convert(
            helper: BaseViewHolder,
            item: DirectBuyOrderList.DataBean.ListBean.GoodsItemBean
        ) {
            GlideHelper.loadRoundTrans(context, item.thumb, helper.getView(R.id.ivPic), 6)
            helper.setText(R.id.tvTitle, item.name)
            helper.setText(R.id.tvSecondTitle, item.goods_spec)
        }

    }
}